package cn.softgame.cms.open.authentication.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.softgame.cms.open.authentication.domain.SysModule;
import cn.softgame.cms.open.authentication.domain.SysUser;
import cn.softgame.cms.open.authentication.persistence.SysUserMapper;

@Service
public class SysUserService {

  @Autowired
  private SysUserMapper sysUserMapper;

  /**
   * 根据用户名获取用户信息
   * @param username 用户名
   * @return
   */
  public SysUser getSysUser(String username) {
	  SysUser sysUser = sysUserMapper.getSysUserByLoginName(username);
	  if("sa".equals(username)){
		  sysUser.setSysModules(sysUserMapper.getSysModules());
	  }
	  // 组装模块树
	  List<SysModule> modules = sysUser.getSysModules();
	  List<SysModule> moduleList = buildModuleTree(modules);
	  sysUser.setSysModules(moduleList);
	  return sysUser;
  }
  
  private List<SysModule> buildModuleTree(List<SysModule> modules){
	  List<SysModule> roots = new ArrayList<SysModule>();
	  
	  Map<String,List<SysModule>> map = new HashMap<String,List<SysModule>>();
	  if(modules!=null && modules.size()>0){
		  for(SysModule m : modules){
			  String parentModuleId = m.getParentModuleId();
			  List<SysModule> children = map.get(parentModuleId);
			  if(children==null){
				  children = new ArrayList<SysModule>();
			  }
			  children.add(m);
			  map.put(parentModuleId, children);
			  if(parentModuleId==null || "0".equals(parentModuleId)){
				  roots.add(m);
			  }
		  }
		  recursion(roots,map);
	  }
	  return roots;
  }
  
  private void recursion(List<SysModule> childs,Map<String,List<SysModule>> map){
	  for(SysModule m : childs){
		  String parentModuleId = m.getModuleId();
		  List<SysModule> children = map.get(parentModuleId);
		  if(children==null)
			  return;
		  m.setChildren(children); 
		  recursion(children,map);
	  }
	  
  }
  
}
